<template>
  <div class="app-container">
    <el-card>
      <div style="display:flex; gap:8px; align-items:center; margin-bottom:12px">
        <el-input v-model="query.groupName" placeholder="分组名称" clearable style="width:240px" />
        <el-button type="primary" @click="load">查询</el-button>
        <el-button @click="reset">重置</el-button>
        <el-button type="success" @click="openCreate">新增分组</el-button>
      </div>
      
      <!-- 使用树形表格 -->
      <el-table 
        :data="treeData" 
        border 
        stripe
        row-key="groupId"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :default-expand-all="true"
      >
        <el-table-column prop="groupName" label="分组名称" min-width="200" />
        <el-table-column prop="description" label="描述" min-width="220" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.status === '0'" type="success">正常</el-tag>
            <el-tag v-else-if="row.status === '1'" type="danger">停用</el-tag>
            <el-tag v-else type="info">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="() => openCreate(row)">新增子分组</el-button>
            <el-button size="small" @click="() => openEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="() => doRemove(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="dialog.visible" :title="dialog.isEdit ? '编辑分组' : '新增分组'" width="520px" @close="closeDialog">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="88px">
        <el-form-item label="上级分组" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="groupOptions"
            :props="{ value: 'groupId', label: 'groupName', children: 'children' }"
            placeholder="请选择上级分组"
            clearable
            check-strictly
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="分组名称" prop="groupName">
          <el-input v-model="form.groupName" placeholder="请输入分组名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="orderNum">
          <el-input-number v-model="form.orderNum" placeholder="请输入显示顺序" style="width: 100%" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="doSubmit" :loading="buttonLoading">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listDeviceGroup, treeDeviceGroup, getDeviceGroup, addDeviceGroup, updateDeviceGroup, delDeviceGroup } from '@/api/iot/device-group'
import { handleTree } from '@/utils/ruoyi'
import type { IotDeviceGroupVO, IotDeviceGroupQuery, IotDeviceGroupForm } from '@/api/iot/device-group/types'

const query = reactive<IotDeviceGroupQuery>({ groupName: '' })
const rows = ref<IotDeviceGroupVO[]>([])
const treeData = ref<IotDeviceGroupVO[]>([])
const groupOptions = ref<IotDeviceGroupVO[]>([])

const dialog = reactive({ visible: false, isEdit: false })
const form = ref<IotDeviceGroupForm>({})
const formRef = ref()
const buttonLoading = ref(false)

const rules = reactive({
  groupName: [{ required: true, message: '分组名称不能为空', trigger: 'blur' }]
})

const initFormData: IotDeviceGroupForm = {
  groupId: undefined,
  groupName: '',
  parentId: 0,
  description: '',
  orderNum: 0,
  status: '0'
}

async function load() {
  try {
    const response = await listDeviceGroup(query)
    
    // 参考设备列表的修正方式
    if (response && response.rows && Array.isArray(response.rows)) {
      rows.value = response.rows
    } else if (response && response.data && Array.isArray(response.data)) {
      rows.value = response.data
    } else if (Array.isArray(response)) {
      rows.value = response
    } else {
      rows.value = []
    }
    
    // 构建树形数据
    treeData.value = handleTree(rows.value, 'groupId', 'parentId', 'children')
  } catch (error) {
    console.error('加载分组数据失败：', error)
    ElMessage.error('加载分组数据失败')
  }
}

function reset() {
  query.groupName = ''
  load()
}

async function loadOptions() {
  try {
    const response = await treeDeviceGroup()
    
    // 参考设备列表的修正方式
    if (response && response.rows && Array.isArray(response.rows)) {
      groupOptions.value = response.rows
    } else if (response && response.data && Array.isArray(response.data)) {
      groupOptions.value = response.data
    } else if (Array.isArray(response)) {
      groupOptions.value = response
    } else {
      groupOptions.value = []
    }
  } catch (error) {
    console.error('加载分组选项失败：', error)
  }
}

function openCreate(parentRow?: IotDeviceGroupVO) {
  dialog.visible = true
  dialog.isEdit = false
  form.value = {
    ...initFormData,
    parentId: parentRow?.groupId || 0
  }
  
  // 重新构建选项（排除当前分组）
  groupOptions.value = buildGroupOptions(rows.value, undefined)
}

function openEdit(row: IotDeviceGroupVO) {
  dialog.visible = true
  dialog.isEdit = true
  form.value = { ...row }
  
  // 重新构建选项（排除当前分组及其子分组）
  groupOptions.value = buildGroupOptions(rows.value, row.groupId)
}

function buildGroupOptions(list: IotDeviceGroupVO[], excludeId?: number): IotDeviceGroupVO[] {
  const options: IotDeviceGroupVO[] = []
  
  function addOption(item: IotDeviceGroupVO, level = 0) {
    if (item.groupId !== excludeId) {
      const option = { ...item }
      option.groupName = '　'.repeat(level) + item.groupName
      options.push(option)
      
      if (item.children) {
        item.children.forEach(child => addOption(child, level + 1))
      }
    }
  }
  
  list.forEach(item => {
    if (item.parentId === 0 || !item.parentId) {
      addOption(item)
    }
  })
  
  return options
}

function closeDialog() {
  dialog.visible = false
  resetForm()
}

function cancel() {
  dialog.visible = false
  resetForm()
}

function resetForm() {
  form.value = JSON.parse(JSON.stringify(initFormData))
  nextTick(() => {
    formRef.value?.resetFields()
  })
}

async function doSubmit() {
  if (!formRef.value) return
  
  await formRef.value.validate()
  buttonLoading.value = true
  
  try {
    if (dialog.isEdit) {
      await updateDeviceGroup(form.value)
    } else {
      await addDeviceGroup(form.value)
    }
    ElMessage.success('保存成功')
    dialog.visible = false
    load()
  } catch (error) {
    console.error('保存失败:', error)
  } finally {
    buttonLoading.value = false
  }
}

async function doRemove(row: IotDeviceGroupVO) {
  await ElMessageBox.confirm(`确认删除分组「${row.groupName}」吗？`, '提示', { type: 'warning' })
  await delDeviceGroup(row.groupId!)
  ElMessage.success('已删除')
  load()
}

onMounted(() => {
  load()
  loadOptions()
})
</script> 